package com.ukit.todolist_xml

import android.os.Build
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.ukit.todolist_xml.RoomRepository.ToDoItem
import com.ukit.todolist_xml.RoomRepository.ToDoItemDao
import com.ukit.todolist_xml.RoomRepository.ToDoItemDatabase
import com.ukit.todolist_xml.databinding.ActivityMainBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var todoItemDatabase: ToDoItemDatabase
    private lateinit var todoItemDao: ToDoItemDao

    @RequiresApi(Build.VERSION_CODES.O)
    private var items = mutableListOf<ToDoItem>()
    private var count = 0

    private  val todoListAdapter = TodoListAdapter(this)

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        todoItemDatabase = ToDoItemDatabase.getDatabase(this)
        todoItemDao = todoItemDatabase.toDoItemDao()

        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        todoListAdapter.setData(items)
        binding.recyclerView.adapter = todoListAdapter

        binding.addItem.setOnClickListener(){
            val dialogFragment = AddItemDialogFragment()
            dialogFragment.show(supportFragmentManager, "AddItemDialogFragment")
        }

        GlobalScope.launch(Dispatchers.IO) {
            items = todoItemDao.getAllItems()
            items.sortByDescending { !it.completed }
            updateList(items)
            updateProgressBar(items)
        }

    }

    private fun updateList(items: List<ToDoItem>) {
        runOnUiThread {
            todoListAdapter.setData(items)
            updateProgressBar(items)
        }
    }

    fun addItemToList(newItemInfo: String) {
        val newItem = ToDoItem(info = newItemInfo)
        GlobalScope.launch(Dispatchers.IO) {
            todoItemDao.insert(newItem)
            val items = todoItemDao.getAllItems()
            items.sortByDescending { !it.completed }
            updateList(items)
        }
    }

    private fun updateProgressBar(items: List<ToDoItem>) {
        var completedCount = 0
        for (item in items) {
            if (item.completed) {
                completedCount++
            }
        }

        if (items.isNotEmpty()) {
            val progress = (completedCount.toFloat() / items.size.toFloat()) * 100
            binding.progressBar.progress = progress.toInt()
        } else {
            binding.progressBar.progress = 0
        }
    }
    fun onCheckBoxClick(position: Int, isChecked: Boolean) {
        val updatedItems = items.toMutableList()
        val item = updatedItems[position]
        item.completed = isChecked
        GlobalScope.launch(Dispatchers.IO) {
            todoItemDao.updateCompleted(item.id, item.completed)
        }
        updatedItems.sortByDescending { !it.completed }
        updateList(updatedItems)
        updateProgressBar(updatedItems)
    }

}
